import os
import sys
import threading

class SafeEmailFetcher:
    def __init__(self):
        # 检查文件是否存在
        base_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
        self.file_path = os.path.join(base_dir, 'configs/邮箱账号.txt')
        self.lock = threading.Lock()

    def get_next_email(self):
        with self.lock:
            # 读取所有邮箱
            try:
                with open(self.file_path, 'r', encoding='utf-8') as f:
                    # 读取非空行并去除换行符
                    lines = [line.strip() for line in f if line.strip()]
            except FileNotFoundError:
                raise FileNotFoundError('邮箱文件不存在')
            # 如果列表为空
            if not lines:
                raise RuntimeError('邮箱文件数据为空')
            # 取第一行（去除换行符）
            email = lines[0]
            # 更新文件内容（去除第一行）
            with open(self.file_path, 'w', encoding='utf-8') as f:
                for line in lines[1:]:
                    f.write(line + '\n')
            return email
